<template>
  <div class="ethernet-settings">
    <div class="top-box">
      <v-container fluid>
        <v-row align="center">
          <v-col cols="3" class="d-flex justify-center text-center">
            <div class="config-item">
              设备名
              <v-tooltip bottom>
                <template v-slot:activator="{ on }">
                  <span v-on="on" style="color: red;">
                    <span aria-hidden="true">*</span>
                  </span>
                </template>
                <span>必填项</span>
              </v-tooltip>
            </div>
          </v-col>
          <v-col cols="9" class="d-flex text-center">
            <v-text-field
                v-model="deviceName"
                label="请输入设备名"
                class="config-content"
                requeired
                dense
                hide-details
                outlined
                :error-messages="devErr ? [devErr] : []"></v-text-field>
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="3" class="d-flex justify-center text-center">
            <div class="config-item">
              SN
              <v-tooltip bottom>
                <template v-slot:activator="{ on }">
                  <span v-on="on" style="color: red;">
                    <span aria-hidden="true">*</span>
                  </span>
                </template>
                <span>必填项</span>
              </v-tooltip>
            </div>
          </v-col>
          <v-col cols="9" class="d-flex text-center" align-self="start">
            <v-text-field
                v-model="SN"
                label="SN"
                class="config-content"
                required
                dense
                hide-details
                outlined
                :error-messages="SNErr ? [SNErr] : []"></v-text-field>
          </v-col>
        </v-row>
        <v-row align="center">
          <v-col cols="3" class="d-flex justify-center text-center" align-self="start">
            <div>
              备注
            </div>
          </v-col>
          <v-col cols="9" class="d-flex text-center" align-self="start">
            <v-textarea
                v-model="note"
                label="输入设备描述信息"
                class="config-content"
                required
                dense
                hide-details
                rows="1"
                auto-grow
                outlined
            ></v-textarea>
          </v-col>
        </v-row>
      </v-container>
    </div>
    <div class="bottom-box">
      <v-container fluid>
        <v-row align="center" justify="center">
          <v-btn @click="commit" class="refresh-btn"
                 style="background-color: #003366; color: white; margin-right: 10px;">提交
          </v-btn>
          <v-btn class="save-btn" @click="cancel" style="background-color: #FFA500; color: white;">取消</v-btn>
        </v-row>
      </v-container>
    </div>
  </div>
</template>

<script>
// import axios from "axios";

// const data = {
//   configValue1: "",
//   configValue2: "",
//   configValue3: "",
//   configValue4: ""
// };
import jwt_decode from "jwt-decode";
import axios from "axios";

export default {
  name: 'EthernetSettingsContent',
  mounted() {
    if (this.localSN) this.SN = this.localSN;
  },
  data() {
    return {
      deviceName: "",
      SN: "",
      note: '',
      devErr: '',
      SNErr: '',
      localSN: localStorage.getItem('sn')
    };
  },
  methods: {
    async commit() {
      this.$refresh();
      this.devErr = '';
      this.SNErr = '';
      if (!this.deviceName) {
        this.devErr = '设备名不能为空！';
        return;
      }
      if (this.deviceName.length > 20) {
        this.devErr = '设备名不能超过20个汉字！'
      }
      if (!this.SN) {
        this.SNErr = 'SIN不能为空！';
        return;
      }
      // 提交逻辑
      const token = localStorage.getItem('token');
      const tenantId = jwt_decode(token).tenantId
      // console.log(tenantId)
      const registerData = {
        sn: this.SN,
        deviceName: this.deviceName,
        tenantId: tenantId,
        note: this.note
      }
      const registerResponse = await axios.post(`${this.$serverUrl}/api/device/register`, registerData, {
        headers: {
          'X-Authorization': `Bearer ${token}`
        }
      })
          .then(response => {
            // console.log(response)
            if (response.data === "registered") {
              this.$emit('errMsg', '该设备已被注册');
            } else if (response.data === "SN not exist") {
              this.$emit('errMsg', '序列号不存在');
            } else if (response.data === "success") {
              this.$emit('successMsg', `设备 ${this.deviceName} 注册成功`);
              localStorage.setItem('sn', this.SN);
            } else {
              // console.log(response)
              this.$emit('errMsg', '注册失败，请检查配置！');
            }
            return response;
          })
          .catch(error => {
            // console.log(error)
            if (error.code === "ERR_BAD_RESPONSE") this.$emit('errMsg', '该设备名已存在！');
            else if (error.response) this.$emit('errMsg', '请求已发送，无响应');
            else this.$emit('errMsg', '配置错误');
            return error;
          })
      // console.log(registerResponse)
      if (registerResponse.data === "success") {
        axios.post(`${this.$serverUrl}/api/device/getIp`, registerData, {
          headers: {
            "X-Authorization": `Bearer ${localStorage.getItem('token')}`
          }
        })
            .then(response => {
              // console.log(response)
              const info = {
                "cmd": 245,
                "config": {
                  "node": {
                    "ipaddr": response.data,
                    "room": localStorage.getItem('room')
                  }
                }
              };
              const JSONINFO = JSON.stringify(info);
              this.$emit('sendData', JSONINFO);
            })
            .catch(error => {
              console.log(error)
            })
      }
    },
    cancel() {
      //取消逻辑
      this.deviceName = "";
      if (this.localSN != null) this.SN = "";
    },
  },
};
</script>

<style scoped>
.ethernet-settings {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
  padding-top: 10vh;
}

.top-box {
  padding: 20px;
  box-sizing: border-box;
  min-width: 500px;
}

.config-item, .config-content {
  text-align: center;
}

.bottom-box {
  display: flex;
  justify-content: center;
  padding: 20px;
  width: 100%;
  border-top: 2px solid #ededed;
}

.bottom-box .refresh-btn {
  background-color: #003366;
  color: white;
  margin-right: 10px;
}

.bottom-box .save-btn {
  background-color: #FFA500;
  color: white;
}
</style>
